package com.whfc.iot.handler;

import com.whfc.iot.session.SessionManager;
import com.whfc.iot.util.ChannelUtil;
import com.whfc.iot.util.LoggingUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2018/11/29 10:41
 */
public class DefaultServerHandler extends ChannelDuplexHandler {

    private Logger logger = LoggerFactory.getLogger(DefaultServerHandler.class);

    public DefaultServerHandler() {
        super();
    }

    public SessionManager getSessionManager() {
        return null;
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.debug("{}", LoggingUtil.format(ctx, "REGISTERED"));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.debug("{}", LoggingUtil.format(ctx, "UNREGISTERED"));
        //删除session
        SessionManager sessionManager = getSessionManager();
        if (sessionManager != null) {
            sessionManager.delete(ctx.channel().id().asLongText());
        }
        //关闭连接
        ctx.close().addListener(future -> {
            logger.info("主动关闭连接结果={}", future.isSuccess());
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.debug("{}", LoggingUtil.format(ctx, "ACTIVE"));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.debug("{}", LoggingUtil.format(ctx, "INACTIVE"));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("{}", LoggingUtil.format(ctx, "CHANNEL_READ", msg));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //logger.info("{}", LoggingUtil.format(ctx, "READ COMPLETE"));

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //空闲事件
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //读空闲
            if (IdleState.READER_IDLE.equals(event.state())) {
                logger.info("读空闲事件,关闭连接,{}", ctx.channel());
                //删除session
                SessionManager sessionManager = getSessionManager();
                if (sessionManager != null) {
                    sessionManager.delete(ctx.channel().id().asLongText());
                }
                //关闭连接
                ctx.close().addListener(future -> {
                    logger.info("空闲关闭连接结果={}", future.isSuccess());
                });
            }
        }
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.debug("{}", LoggingUtil.format(ctx, "WRITABILITY CHANGED"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (ChannelUtil.isSLBCheck(ctx.channel())) {
            return;
        }
        logger.info("exceptionCaught,ctx:{},cause:{}", ctx, cause);
        ctx.close().addListener(future -> {
            logger.info("异常关闭连接结果={}", future.isSuccess());
        });
    }
}
